package com.centling.task;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.centling.business.OrderVO;
import com.centling.service.IAxis2Service;
import com.centling.service.IOrderService;

@Component
@Transactional
public class OrderInfoImportTasks {

	private static Logger log = Logger.getLogger(OrderInfoImportTasks.class);

	@Resource
	protected IAxis2Service axis2Service;
	
	@Resource
	protected IOrderService orderService;

	@Value("${task.order.import.daynum}")
	private Integer daynum;
	
	/**
	 * This task will be performed every 30 minutes
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	@Scheduled(cron = "0 0/${task.order.import.mintus} * * * *")
	@Transactional
	private void ordersInfoImportCRM() throws Exception {
		log.info("ordersInfoImportCRM task invoke...");
		
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)+daynum);
		Date bDate = calendar.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		String beginDate = sdf.format(bDate);
		String endDate   = sdf.format(date);
		log.info("task request beginDate: " + beginDate);
		log.info("task request endDate  : " + endDate);
		
		Map<String,Object> map = axis2Service.getOrdersFromBL(beginDate, endDate, orderService.getNoDeliveryOrderIDs());

		List<OrderVO> volist = (List<OrderVO>) map.get("OrderVOList");
		List<String[]> orderstatuslist = (List<String[]>) map.get("OrderStatusList");
		
		log.info("axis2Service.getOrdersFromBL return OrderVOList.size()="+((volist==null||volist.isEmpty())?0:volist.size())
				+", OrderStatusList.size()="+((orderstatuslist==null||orderstatuslist.isEmpty())?0:orderstatuslist.size()));
		
		orderService.processOrdersBL(volist, orderstatuslist);
		
		log.info("ordersInfoImportCRM task end...");
	}
}
